﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace SR_MessageDemo.Messages
{
    public class WeakReferenceMessager : IMessage
    {
        public static WeakReferenceMessager Default { get; }
        = new WeakReferenceMessager();


        private Dictionary<Type, HashSet<object>>
             messgerDict = new Dictionary<Type, HashSet<object>>();

        public void Regisit<TValue>(IRecipiet<TValue> recipiet)
        {
            lock (messgerDict)
            {
                Type type = typeof(TValue);
                if (messgerDict.ContainsKey(type))
                {
                    messgerDict[type].Add(recipiet);
                }
                else
                {
                    HashSet<object> hash = new HashSet<object> { recipiet };
                    messgerDict.Add(type, hash);
                }
            }
           
        }

        public void Send<TValue>(TValue value)
        {
            Type type = typeof(TValue);
            if (messgerDict.ContainsKey(type))
            {
                HashSet<object> hashSets = messgerDict[type];
                foreach (var item in hashSets)
                {
                    if(item is IRecipiet<TValue> ir)
                    {
                        ir.Recive(value);
                    }
                }
            }
        }

       /* public void UnRegisitAll<TValue>(IRecipiet<TValue> recipiet)
        {
            lock (messgerDict)
            {
                Type type = typeof(TValue);
                if (messgerDict.ContainsKey(type))
                {
                    HashSet<object> hash = messgerDict[type];
                    foreach (var item in hash)
                    {
                        hash.Remove(item);
                    }
                }
            }
        }*/
    }
}
